package com.showworkflow.service;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;

import java.io.IOException;


// apikey: app-5l8lKMSJpvo1VzKrXtnzO3Rl
@Service
public class DifyService {

    private static final String API_BASE_URL = "http://47.108.14.196:41026/v1";
    private static final String API_KEY = "app-lE5OHQi6JWolQa9syYflPwal";

    public String processFilesToDify(MultipartFile file1, MultipartFile file2) throws IOException {
        // 步骤1: 上传文件获取upload_file_id
        String fileId1 = uploadFile(file1);
        String fileId2 = uploadFile(file2);

        // 步骤2: 使用文件ID运行workflow
        return runWorkflowWithFiles(fileId1, fileId2);
    }

    public String generateInterrogationRecord(String caseApprovalContent) throws IOException {
        System.out.println("开始生成笔录，立案审批表内容: " + caseApprovalContent);

        // 步骤1: 将立案审批表内容创建为临时文件并上传到Dify
        String fileId = uploadContentAsFile(caseApprovalContent, "case_approval_content.txt");
        System.out.println("文件上传成功，fileId: " + fileId);

        // 步骤2: 使用文件ID运行笔录工作流
        return runInterrogationWorkflowWithFile(fileId);
    }

    private String uploadContentAsFile(String content, String filename) throws IOException {
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpPost httpPost = new HttpPost(API_BASE_URL + "/files/upload");

            // 构建multipart请求体，将文本内容作为文件上传
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            builder.addBinaryBody("file", content.getBytes("UTF-8"),
                org.apache.http.entity.ContentType.TEXT_PLAIN,
                filename);
            builder.addTextBody("user", "吴彦祖");

            // 使用笔录工作流的API KEY
            httpPost.setHeader("Authorization", "Bearer app-rnUdpZdkvDEfbLvncgik3VMO");
            httpPost.setEntity(builder.build());

            try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
                int statusCode = response.getStatusLine().getStatusCode();
                String responseBody = EntityUtils.toString(response.getEntity());

                if (statusCode < 200 || statusCode >= 300) {
                    throw new IOException("内容文件上传失败，状态码: " + statusCode + ", 响应: " + responseBody);
                }

                // 解析响应获取upload_file_id
                ObjectMapper mapper = new ObjectMapper();
                JsonNode jsonNode = mapper.readTree(responseBody);
                return jsonNode.get("id").asText();
            }
        } catch (Exception e) {
            throw new IOException("上传内容文件失败: " + e.getMessage(), e);
        }
    }

    private String runInterrogationWorkflowWithFile(String fileId) throws IOException {
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpPost httpPost = new HttpPost(API_BASE_URL + "/workflows/run");

            // 构建JSON请求体
            ObjectMapper mapper = new ObjectMapper();
            ObjectNode jsonRequest = mapper.createObjectNode();

            // 设置inputs参数，input3作为文件对象
            ObjectNode inputsNode = mapper.createObjectNode();
            ObjectNode input3FileNode = mapper.createObjectNode();
            input3FileNode.put("type", "document");
            input3FileNode.put("transfer_method", "local_file");
            input3FileNode.put("upload_file_id", fileId);
            inputsNode.set("input3", input3FileNode);
            jsonRequest.set("inputs", inputsNode);

            jsonRequest.put("response_mode", "blocking");
            jsonRequest.put("user", "吴彦祖");

            // 添加files数组
            ArrayNode filesArray = mapper.createArrayNode();
            ObjectNode fileNode = mapper.createObjectNode();
            fileNode.put("type", "document");
            fileNode.put("transfer_method", "local_file");
            fileNode.put("upload_file_id", fileId);
            filesArray.add(fileNode);
            jsonRequest.set("files", filesArray);

            String jsonString = mapper.writeValueAsString(jsonRequest);
            System.out.println("发送到笔录工作流的请求JSON: " + jsonString);

            // 设置请求头和请求体，使用笔录工作流的API KEY
            httpPost.setHeader("Authorization", "Bearer app-rnUdpZdkvDEfbLvncgik3VMO");
            httpPost.setHeader("Content-Type", "application/json");
            httpPost.setEntity(new StringEntity(jsonString, "UTF-8"));

            // 执行请求
            try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
                int statusCode = response.getStatusLine().getStatusCode();
                String responseBody = EntityUtils.toString(response.getEntity());

                System.out.println("笔录工作流响应状态码: " + statusCode);
                System.out.println("笔录工作流响应内容: " + responseBody);

                if (statusCode < 200 || statusCode >= 300) {
                    throw new IOException("笔录Workflow执行失败，状态码: " + statusCode + ", 响应: " + responseBody);
                }

                if (responseBody == null) {
                    throw new IOException("笔录Dify返回空响应");
                }

                String trimmedBody = responseBody.trim();
                if (!trimmedBody.startsWith("{") && !trimmedBody.startsWith("[")) {
                    throw new IOException("笔录Dify返回了非JSON响应. 状态码: " + statusCode +
                        ", 响应头: " + response.getAllHeaders() +
                        ", 响应体: " + responseBody);
                }

                return responseBody;
            }
        } catch (Exception e) {
            throw new IOException("运行笔录workflow失败: " + e.getMessage(), e);
        }
    }

    private String uploadFile(MultipartFile file) throws IOException {
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpPost httpPost = new HttpPost(API_BASE_URL + "/files/upload");

            // 构建multipart请求体上传文件
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            builder.addBinaryBody("file", file.getBytes(),
                org.apache.http.entity.ContentType.APPLICATION_OCTET_STREAM,
                file.getOriginalFilename());
            builder.addTextBody("user", "吴彦祖");

            httpPost.setHeader("Authorization", "Bearer " + API_KEY);
            httpPost.setEntity(builder.build());

            try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
                int statusCode = response.getStatusLine().getStatusCode();
                String responseBody = EntityUtils.toString(response.getEntity());

                if (statusCode < 200 || statusCode >= 300) {
                    throw new IOException("文件上传失败，状态码: " + statusCode + ", 响应: " + responseBody);
                }

                // 解析响应获取upload_file_id
                ObjectMapper mapper = new ObjectMapper();
                JsonNode jsonNode = mapper.readTree(responseBody);
                return jsonNode.get("id").asText();
            }
        } catch (Exception e) {
            throw new IOException("上传文件失败: " + e.getMessage(), e);
        }
    }

    private String runWorkflowWithFiles(String fileId1, String fileId2) throws IOException {
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpPost httpPost = new HttpPost(API_BASE_URL + "/workflows/run");

            // 构建JSON请求体
            ObjectMapper mapper = new ObjectMapper();
            ObjectNode jsonRequest = mapper.createObjectNode();

            // 设置inputs参数，引用上传的文件
            ObjectNode inputsNode = mapper.createObjectNode();

            // input1作为文件对象
            ObjectNode input1FileNode = mapper.createObjectNode();
            input1FileNode.put("type", "document");
            input1FileNode.put("transfer_method", "local_file");
            input1FileNode.put("upload_file_id", fileId1);
            inputsNode.set("input1", input1FileNode);

            // input2作为文件对象
            ObjectNode input2FileNode = mapper.createObjectNode();
            input2FileNode.put("type", "document");
            input2FileNode.put("transfer_method", "local_file");
            input2FileNode.put("upload_file_id", fileId2);
            inputsNode.set("input2", input2FileNode);

            jsonRequest.set("inputs", inputsNode);

            jsonRequest.put("response_mode", "blocking");
            jsonRequest.put("user", "吴彦祖");

            // 添加files数组
            ArrayNode filesArray = mapper.createArrayNode();

            ObjectNode file1Node = mapper.createObjectNode();
            file1Node.put("type", "document");
            file1Node.put("transfer_method", "local_file");
            file1Node.put("upload_file_id", fileId1);
            filesArray.add(file1Node);

            ObjectNode file2Node = mapper.createObjectNode();
            file2Node.put("type", "document");
            file2Node.put("transfer_method", "local_file");
            file2Node.put("upload_file_id", fileId2);
            filesArray.add(file2Node);

            jsonRequest.set("files", filesArray);

            String jsonString = mapper.writeValueAsString(jsonRequest);

            // 设置请求头和请求体
            httpPost.setHeader("Authorization", "Bearer " + API_KEY);
            httpPost.setHeader("Content-Type", "application/json");
            httpPost.setEntity(new StringEntity(jsonString, "UTF-8"));

            // 执行请求
            try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
                int statusCode = response.getStatusLine().getStatusCode();
                String responseBody = EntityUtils.toString(response.getEntity());

                if (statusCode < 200 || statusCode >= 300) {
                    throw new IOException("Workflow执行失败，状态码: " + statusCode + ", 响应: " + responseBody);
                }

                if (responseBody == null) {
                    throw new IOException("Dify返回空响应");
                }

                String trimmedBody = responseBody.trim();
                if (!trimmedBody.startsWith("{") && !trimmedBody.startsWith("[")) {
                    throw new IOException("Dify返回了非JSON响应. 状态码: " + statusCode +
                        ", 响应头: " + response.getAllHeaders() +
                        ", 响应体: " + responseBody);
                }

                return responseBody;
            }
        } catch (Exception e) {
            throw new IOException("运行workflow失败: " + e.getMessage(), e);
        }
    }
}